import 'dart:io';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:qunaimedical/init/provider.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/utils/log_util.dart';
import 'package:qunaimedical/utils/sp_util.dart';
import 'package:qunaimedical/values/urls.dart';
import 'package:webview_flutter/webview_flutter.dart';

class AuthUtil {
  AuthUtil._();

  static final String _tag = 'AuthUtil';

  static bool isLogin() {
    return SPUtil.getQAUser() != null;
  }

  /// 退出登录
  static void logout(BuildContext context) {
    context.read<StoreInfo>().clear();
  }

  /// 获取cookie
  static Future<Cookie?> _getCookie() async {
    var cookies =
        await XHttp.cookieJar.loadForRequest(Uri.parse(Urls.BASE_URL));
    if (cookies.isNotEmpty) {
      var cookie = cookies.first;
      Log.d(_tag, "cookie:${cookie.name}/${cookie.value}");
      return cookie;
    }
    Log.d(_tag, "cookie:null");
    return null;
  }

  static Future<WebViewCookie?> genarateWebViewCookie() async {
    var cookie = await _getCookie();
    if (cookie != null) {
      return WebViewCookie(
        name: cookie.name,
        value: cookie.value,
        domain: Urls.DOMAIN,
      );
    } else {
      return null;
    }
  }
}
